package service.impl;

import constant.Constant;
import dao.ResideMapper;
import dao.SubscriptionDtlMapper;
import dao.SubscriptionMapper;
import entity.Reside;
import entity.Subscription;
import entity.SubscriptionDtl;
import framework.bean.factory.ObjectFactory;
import framework.bean.factory.annotation.Component;
import service.SubscriptionService;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component("subscriptionServiceTarget")
public class SubscriptionServiceImpl implements SubscriptionService {
    @Override
    public List<Subscription> findUnacknowledged(Integer memberId) {

        SubscriptionMapper subscriptionMapper= (SubscriptionMapper) ObjectFactory.getObject("subscriptionMapper");

        List<Subscription> subscriptions=subscriptionMapper.selectByMidAndStatuses(memberId,new String[]{Constant.SubscriptionStatus.SUBSCRIPTION_STATUS_UNACKNOWLEDGED});

        return subscriptions;
    }

    @Override
    public List<Subscription> findHistorical(Integer memberId) {
        SubscriptionMapper subscriptionMapper= (SubscriptionMapper) ObjectFactory.getObject("subscriptionMapper");

        List<Subscription> subscriptions=subscriptionMapper.selectByMidAndStatuses(memberId,new String[]{Constant.SubscriptionStatus.SUBSCRIPTION_STATUS_ACKNOWLEDGED,
                                                                                                         Constant.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED});

        return subscriptions;
    }

    @Override
    public void addDetail(List<SubscriptionDtl> subscriptionDtls) {

        SubscriptionDtlMapper subscriptionDtlMapper= (SubscriptionDtlMapper) ObjectFactory.getObject("subscriptionDtlMapper");
        ResideMapper resideMapper= (ResideMapper) ObjectFactory.getObject("resideMapper");

        for (SubscriptionDtl subscriptionDtl : subscriptionDtls) {
//            Double price=数据库查询房间单价*天数
//            subscriptionDtl.setPrice(price);


            //调用持久层保存明细
            subscriptionDtlMapper.insert(subscriptionDtl);

            //根据开始日期和结束日期，每天往居住信息表中插入一条记录
            Date startDate=subscriptionDtl.getSdate();
            Date endDate=subscriptionDtl.getEdate();

            Calendar startCal=Calendar.getInstance();
            startCal.setTime(startDate);
            Calendar endCal=Calendar.getInstance();
            endCal.setTime(endDate);

            while(startCal.before(endCal)){

                Reside reside=new Reside();
//                reside.setSubscriptionDtl(subscriptionDtl);
//                reside.setResidedate(startCal.getTime());

                resideMapper.insert(reside);

                startCal.add(Calendar.DAY_OF_MONTH,1);

            }
        }


    }
}
